package com.init.iblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.init.iblog.domain.ResponseResult;
import com.init.iblog.domain.dto.UserDto;
import com.init.iblog.domain.entity.User;
import com.init.iblog.domain.vo.PageVo;
import com.init.iblog.domain.vo.UserInfoVo;
import com.init.iblog.enums.AppHttpCodeEnum;
import com.init.iblog.exception.SystemException;
import com.init.iblog.mapper.UserMapper;
import com.init.iblog.service.UserService;
import com.init.iblog.utils.BeanCopyUtils;
import com.init.iblog.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2023-02-23 20:37:38
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired(required = false)
    private UserMapper userMapper;

    /**
     * 查询用户个人信息
     * @return
     */
    @Override
    public ResponseResult userInfo() {

        //获取用户当前id
        Long userId = SecurityUtils.getUserId();
        //根据用户id查询用户信息
        User user = getById(userId);
        //封装成UserInfoVo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    /**
     * 更新用户个人信息
     * @param user
     * @return
     */
    @Override
    public ResponseResult updateUserInfo(User user) {
        updateById(user);
        return ResponseResult.okResult();
    }

    /**
     * 用户注册
     * @return
     */
    @Override
    public ResponseResult register(User user) {

        //对数据进行非空判断   null ""
        if(!StringUtils.hasText(user.getName())){    //StringUtils.hasText有内容返回true
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }

        if(!StringUtils.hasText(user.getNickname())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }

        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }

        if(!StringUtils.hasText(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_NOT_NULL);
        }



        //对数据进行是否存在判断
        if(userNameExist(user.getName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }

        if(emailExist(user.getEmail())){
            throw new SystemException(AppHttpCodeEnum.EMAIL_EXIST);
        }

        //对密码进行进行加密处理
        String encodePassword = passwordEncoder.encode(user.getPassword());

        user.setPassword(encodePassword);
        //存入数据库中
        save(user);
        return ResponseResult.okResult();
    }

    /**
     * 查询用户信息列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult<PageVo> getUserList(Integer pageNum, Integer pageSize, UserDto userDto) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(userDto.getName()),User::getName,userDto.getName());
        queryWrapper.eq(StringUtils.hasText(userDto.getPhonenumber()),User::getPhonenumber,userDto.getPhonenumber());
        queryWrapper.eq(StringUtils.hasText(userDto.getStatus()),User::getStatus,userDto.getStatus());
        Page<User> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNum);
        page(page,queryWrapper);
        PageVo pageVo = new PageVo(page.getRecords(),page.getTotal());
        return ResponseResult.okResult(pageVo);
    }


    /**
     * 新增用户
     * @param user
     * @return
     */
    @Override
    public ResponseResult addUser(User user) {
        String name = user.getName();
        boolean flag = userNameExist(name);
        //该用户已注册
        if(flag){
            throw new SystemException(AppHttpCodeEnum.PASSWORD_NOT_NULL);
        }
        //对密码进行进行加密处理
        String encodePassword = passwordEncoder.encode(user.getPassword());

        user.setPassword(encodePassword);
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult resetUserPwd(String passward) {
//        //对密码进行进行加密处理
//        String encodePassword = passwordEncoder.encode(user.getPassword());
//
//        user.setPassword(encodePassword);
        return null;
    }

    @Override
    public ResponseResult deleteUser(List<Long> ids) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        for(Long id:ids){
            userMapper.deleteById(id);
        }
         return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateUser(User user) {

        userMapper.updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult changeUserStatus(Long id, String status) {
        User user = userMapper.selectById(id);
        String status1 = user.getStatus();
        if(status.equals("0")){
            user.setStatus("1");
        }else{
            user.setStatus("0");
        }
        return ResponseResult.okResult();
    }


    /**
     * 判断邮箱是否已存在
     * @param email
     * @return
     */
    private boolean emailExist(String email) {

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getEmail,email);
        return count(lambdaQueryWrapper) > 0;
    }

    /**
     * 判断用户名是否已存在
     * @param name
     * @return
     */
    private boolean userNameExist(String name) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getName,name);
        return count(lambdaQueryWrapper) > 0;
    }
}
